package com.ruoyi.web.controller.api;

import ch.qos.logback.core.joran.util.beans.BeanUtil;
import com.ruoyi.JavaSendMailDemo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.shop.domain.*;
import com.ruoyi.shop.service.*;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.controller.api.vo.CategoryVo;
import com.ruoyi.web.controller.api.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Api("C端商品相关接口")
@RestController
@RequestMapping("/api")
public class ApiGoodsController {


    @Autowired
    private IBannerService bannerService;
    @Autowired
    private ICategoryService categoryService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IUserGoodsSpecialService userGoodsSpecialService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    public RedisTemplate redisTemplate;
    @Autowired
    private IRecipeService recipeService;
    @Autowired
    private IPromotionalService promotionalService;
    @Autowired
    private TokenService tokenService;

    //获取宣传主图接口
    @GetMapping("/getPromotional")
    @ApiOperation("获取宣传主图接口")
    public R getPromotional()
    {
        Promotional promotional = promotionalService.selectPromotionalList(new  Promotional()).get(0);
        return R.ok(promotional);
    }


    @GetMapping("/getRecipeList")
    @ApiOperation("获取食谱列表")
    public R getRecipeList(Long goodsId) {
        Recipe recipe = new Recipe();
        recipe.setGoodsId(goodsId);
        return R.ok(recipeService.selectRecipeList(recipe));
    }

    @GetMapping("/getRecipeById")
    @ApiOperation("获取食谱详情ById")
    public R getRecipeById(String id) {
        return R.ok(recipeService.selectRecipeById(Long.parseLong(id)));
    }


    @GetMapping("/getCode")
    @ApiOperation("获取验证码")
    public R updatePwd(String email) throws Exception {
        //生成6位随机验证码
        String code = UUIDOrderGenerator.generate();
        //保存30分钟消息
        redisTemplate.opsForValue().set(email, code, 30, TimeUnit.MINUTES);
        JavaSendMailDemo.sendEmail(email, code);
        return R.ok();
    }

    @ApiOperation("商城用户忘记密码")
    @PostMapping("/forgetPassword")
    public R forgetPassword(@RequestBody UserVo user) {
        String msg = "";
        String username = user.getUsername();
        String password = user.getPassword();

        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        if (StringUtils.isEmpty(username))
        {
            msg = "用户名不能为空";
            return R.fail(msg);
        }else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            msg = "密码长度必须在5到20个字符之间";
            return R.fail(msg);
        }
        else if (userService.checkUserNameUnique(sysUser))
        {
            msg = "用户'" + username + "'不存在";
            return R.fail(msg);
        }
        else if (StringUtils.isEmpty(user.getCode()))
        {
            msg = "验证码不能为空";
            return R.fail(msg);
        }
        //先模拟验证用123456
        else if (!user.getCode().equals("123456"))
        {
            msg = "验证码错误";
            return R.fail(msg);
        }
//        else if (!user.getCode().equals(redisTemplate.opsForValue().get(user.getUsername())))
//        {
//            msg = "验证码错误";
//            return R.fail(msg);
//        }
        else{
            SysUser sysUser1 = userService.selectUserByUserName(username);
            sysUser.setUserId(sysUser1.getUserId());
            sysUser.setPwdUpdateDate(DateUtils.getNowDate());
            sysUser.setPassword(SecurityUtils.encryptPassword(password));
            userService.resetPwd(sysUser);
        }

        return R.ok();
    }


    @ApiOperation("商城用户注册")
    @PostMapping("/shopUserRegister")
    public R shopUserRegister(@RequestBody UserVo user) {

        String msg = "";
        String username = user.getUsername();
        String password = user.getPassword();

        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        if (StringUtils.isEmpty(username))
        {
            msg = "用户名不能为空";
            return R.fail(msg);
        }
        else if (StringUtils.isEmpty(password))
        {
            msg = "用户密码不能为空";
            return R.fail(msg);
        }
        else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            msg = "账户长度必须在2到20个字符之间";
            return R.fail(msg);
        }
        else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            msg = "密码长度必须在5到20个字符之间";
            return R.fail(msg);
        }
        else if (!userService.checkUserNameUnique(sysUser))
        {
            msg = "保存用户'" + username + "'失败，注册账号已存在";
            return R.fail(msg);
        }
        else if (StringUtils.isEmpty(user.getCode()))
        {
            msg = "验证码不能为空";
            return R.fail(msg);
        }
        else if (!user.getCode().equals("123456"))
        {
            msg = "验证码错误";
            return R.fail(msg);
        }
//        else if (!user.getCode().equals(redisTemplate.opsForValue().get(user.getUsername())))
//        {
//            msg = "验证码错误";
//            return R.fail(msg);
//        }
        else
        {
            sysUser.setNickName(username);
            sysUser.setPwdUpdateDate(DateUtils.getNowDate());
            sysUser.setPassword(SecurityUtils.encryptPassword(password));
            boolean regFlag = userService.registerUser(sysUser);
            if (!regFlag)
            {
                msg = "注册失败,请联系系统管理人员";
                return R.fail(msg);
            }
            else
            {
                //分配权限
                userService.insertUserAuth(sysUser.getUserId(), new Long[]{100L});
//                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.register.success")));
            }
        }


        return R.ok(msg);
    }


    @ApiOperation("获取首页轮播图")
    @GetMapping("/getBannerList")
    public R<List<Banner>> getBannerList() {
        List<Banner> list =  bannerService.selectBannerList(new Banner());
        return R.ok(list);
    }


    @ApiOperation("获取首页商品分类列表")
    @GetMapping("/getCategoryList")
    public R<List<Category>> getCategoryList() {
        List<Category> list =  categoryService.selectCategoryList(new Category());
        return R.ok(list);
    }


    @ApiOperation("获取首页热门商品列表")
    @GetMapping("/getHotGoodsList")
    public R<List<Goods>> getHotGoodsList() {
        List<Goods> list = new  ArrayList<>();
        list =goodsService.getHotGoodsList();
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            list.forEach(item->{
                Goods goods =goodsService.getdetails(item.getId(),loginUser.getUserId());
                item.setSpecial(goods.getSpecial());
            });

        }catch (Exception e){
            System.out.println("用户未登录");

        }


        return R.ok(list);
    }


    @ApiOperation("获取所有商品分类列表")
    @GetMapping("/getCategoryAll")
    public R<List<CategoryVo>> getCategoryAll() {
        List<Category> list =  categoryService.selectCategoryList(new Category());
        List<CategoryVo> categoryVoList = new ArrayList<>();
        list.forEach(item->{
            CategoryVo categoryVo = new CategoryVo();
            Category category = new Category();
            category.setParentId(item.getId());
            List<Category> childrenList = categoryService.selectCategoryList(category);
            categoryVo.setCategory(item);
            categoryVo.setChildrenList(childrenList);
            categoryVoList.add(categoryVo);
        });
        return R.ok(categoryVoList);
    }


    @ApiOperation("根据分类ID获取商品列表")
    @GetMapping("/getGoodsByClassId")
    public R getGoodsByClassId(String classId) {
        List<GoodsVo> list = new ArrayList<>();
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
//            list = userGoodsSpecialService.getGoodsByClassId(classId,loginUser.getUserId());
            list = userGoodsSpecialService.getGoodsByClassIdAndUserId(classId,loginUser.getUserId());

        }catch (Exception e){
            System.out.println("用户未登录");
            Goods goods = new Goods();
            goods.setClassId(Long.parseLong(classId));
            List<Goods> lists = goodsService.selectGoodsList(goods);
            list = lists.stream().map(item->{
                GoodsVo goodsVo = new GoodsVo();
                BeanUtils.copyProperties(item,goodsVo);
                return goodsVo;
            }).collect(Collectors.toList());
        }


        return R.ok(list);
    }


    @ApiOperation("模糊查询商品列表")
    @GetMapping("/getGoodsBySearch")
    public R getGoodsBySearch(String search) {
        List<GoodsVo> list = new ArrayList<>();
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
//            list = userGoodsSpecialService.getGoodsByClassId(classId,loginUser.getUserId());
            list = userGoodsSpecialService.getGoodsBySearchAndUserId(search,loginUser.getUserId());

        }catch (Exception e){
            System.out.println("用户未登录");
            Goods goods = new Goods();
            goods.setGoodName(search);
            List<Goods> lists = goodsService.selectGoodsList(goods);
            list = lists.stream().map(item->{
                GoodsVo goodsVo = new GoodsVo();
                BeanUtils.copyProperties(item,goodsVo);
                return goodsVo;
            }).collect(Collectors.toList());
        }


        return R.ok(list);
    }

    @ApiOperation("根据一级分类ID获取商品列表")
    @GetMapping("/getGoodsByOneClassId")
    public R getGoodsByOneClassId(String classId) {
        List<GoodsVo> list = new ArrayList<>();
        List<Category> children = categoryService.selectChildrenById(classId);
        for (Category child : children) {
            list.addAll(userGoodsSpecialService.getGoodsByClassId(String.valueOf(child.getId())));
        }
        return R.ok(list);
    }
}
